package com.modouyu.novel.core.freemark;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import com.modouyu.novel.entity.NovelArticleEntity;
import com.modouyu.novel.service.NovelArticleService;
import com.modouyu.novel.utils.Freemarker;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2018/5/7.
 */
@Component
public class ArticleList implements TemplateDirectiveModel {

    private Logger logger = LoggerFactory.getLogger(ArticleList.class);

    @Autowired
    private NovelArticleService novelArticleService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        logger.debug("模板map:{}", map);

        String fields = Freemarker.getString(map, "fields");
        String sort = Freemarker.getString(map, "sort");
        Integer pageNum = Freemarker.getInteger(map, "pageNum");
        Integer pageSize = Freemarker.getInteger(map, "pageSize");
        Integer typeid = Freemarker.getInteger(map, "typeid");


        Wrapper<NovelArticleEntity> ew = new EntityWrapper<NovelArticleEntity>();
        if (StringUtils.isNotBlank(fields)) {
            String[] f = StringUtils.split(fields, ",");
            String[] s = StringUtils.split(sort, ",");
            for (int i = 0; i < f.length; i++) {
                boolean b = false;
                if ("asc".equalsIgnoreCase(s[i])) {
                    b = true;
                }
                ew.orderBy(f[i], b);
            }
        }

        if (null != typeid) {
            ew.eq("typeid", typeid);
        }

        Page<NovelArticleEntity> page = new Page<>(pageNum, pageSize);
        page = novelArticleService.selectPage(page, ew);

        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        environment.setVariable("pagedata", builder.build().wrap(page));
        body.render(environment.getOut());
    }
}
